<template>
  <div>
    <div class="app-container">
      <el-row :gutter="20" style="margin: 10px">
        <el-col :span="8" :xs="24">
          <el-card class="box-card">
            <template v-slot:header>
              <div class="clearfix">
                <span style="margin-right: 60px">患者信息</span>
                <el-button
                    type="primary"
                    plain
                    icon="search"
                    size="mini"
                    @click="handlePatientSelect"
                >患者选择</el-button>
              </div>
            </template>
            <div>
              <el-form :model="formPatient" :rules="rulesPatient" ref="formPatient" :inline="true" label-width="80px">
                <el-form-item label="患者姓名" prop="name">
                  <el-input
                      v-model="formPatient.name"
                      clearable
                      style="width: 240px"
                  />
                </el-form-item>
                <el-form-item label="身份证号" prop="idNumber">
                  <el-input
                      v-model="formPatient.idNumber"
                      clearable
                      style="width: 240px"
                  />
                </el-form-item>
                <el-form-item label="电话号码" prop="phone">
                  <el-input
                      v-model="formPatient.phone"
                      clearable
                      style="width: 240px"
                  />
                </el-form-item>
                <el-form-item label="性别" prop="status">
                  <el-radio-group v-model="formPatient.gender" class="ml-4">
                    <el-radio label="男" size="large">男</el-radio>
                    <el-radio label="女" size="large">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                  <el-input
                      v-model="formPatient.age"
                      clearable
                      style="width: 240px"
                  />
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker clearable
                                  v-model="formPatient.birthday"
                                  type="date"
                                  format="YYYY-MM-DD"
                                  value-format="YYYY-MM-DD"
                                  style="width: 240px"
                                  placeholder="请选择生日">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                  <el-input
                      v-model="formPatient.address"
                      clearable
                      style="width: 240px"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" icon="Plus" @click="submitFormPatient">保存</el-button>
                  <el-button icon="Refresh" @click="resetFormPatient">重置</el-button>
                </el-form-item>
              </el-form>

            </div>
          </el-card>
        </el-col>
        <el-col :span="16" :xs="24">
          <el-card>

                <template v-slot:header>
                  <el-row type="flex" class="clearfix">
                    <el-col :span="12">
                      <span>病历编号</span>
                      <template v-if="currentRecordNumber">
                        <span  style="color: blue; margin: 0 20px;">{{currentRecordNumber}}</span>
                      </template>
                      <template v-else>
                        <span  style="color: blue; margin: 0 20px;">请选择病历</span>
                      </template>
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        type="primary"
                        size="mini"
                        icon="search"
                        @click="handleRecordSelect"
                      >选择病历</el-button>
                    </el-col>
                  </el-row>
                </template>

                <el-form :model="formDiagnosis" :rules="rulesDiagnosis" ref="formDiagnosis" :inline="true" v-show="showSearch" label-width="80px">
                  <el-row>
                    <el-col :span="12">
                  <el-form-item label="诊断结果" prop="result">
                    <el-input
                        v-model="formDiagnosis.result"
                        style="width: 700px"
                        type="textarea"
                        :rows="6"
                        placeholder="输入诊断结果"
                    />
                  </el-form-item>

                  <el-form-item label="治疗建议" prop="suggestion">
                    <el-input
                        v-model="formDiagnosis.suggestion"
                        style="width: 700px"
                        type="textarea"
                        :rows="6"
                        placeholder="输入治疗建议"
                    />
                  </el-form-item>

                  <el-form-item label="注意事项" prop="attention">
                    <el-input
                        v-model="formDiagnosis.attention"
                        style="width: 700px"
                        type="textarea"
                        :rows="6"
                        placeholder="输入注意事项"
                    />
                  </el-form-item>
                  <el-form-item label="确诊日期" prop="date">
                    <el-date-picker clearable
                                    v-model="formDiagnosis.date"
                                    type="date"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 240px"
                                    placeholder="输入确诊日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                      <el-button type="primary" icon="check" @click="submitFormDiagnosis">保存</el-button>
                      <el-button icon="Refresh" @click="resetFormDiagnosis">重置</el-button>
                  </el-form-item>
                  </el-col>

                  </el-row>
                </el-form>

          </el-card>
        </el-col>
      </el-row>

    </div>


  <!--  选择患者对话框-->
    <el-dialog :title="titlePatient" v-model="openPatient" width="1000px" append-to-body>
      <el-form :model="queryParamsPatient" ref="queryParamsPatient" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="身份证" prop="idNumber">
          <el-input
              v-model="queryParamsPatient.idNumber"
              placeholder="请输入身份证"
              clearable
              @keyup.enter.native="handleQueryPatient"
          />
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input
              v-model="queryParamsPatient.name"
              placeholder="请输入患者姓名"
              clearable
              @keyup.enter.native="handleQueryPatient"
          />
        </el-form-item>
        <el-form-item label="患者电话" prop="phone">
          <el-input
              v-model="queryParamsPatient.phone"
              placeholder="请输入患者电话"
              clearable
              @keyup.enter.native="handleQueryPatient"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryPatient">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryPatient">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="patientList" highlight-current-row @current-change="handleCurrentChangePatient">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column label="身份证号" align="center" prop="idNumber" />
        <el-table-column label="患者姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender" />
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="电话" align="center" prop="phone" />
        <el-table-column label="地址" align="center" prop="address" />
      </el-table>
      <pagination
          v-show="totalPatient>0"
          :total="totalPatient"
          v-model:page="queryParamsPatient.pageNum"
          v-model:limit="queryParamsPatient.pageSize"
          @pagination="getListPatient"
      />
    </el-dialog>

    <!--  选择病历对话框-->
    <el-dialog :title="titleRecord" v-model="openRecord" width="1000px" append-to-body>
      <el-form :model="queryParamsRecord" ref="queryParamsRecord" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="病历号" prop="medicalRecordId">
          <el-input
              v-model="queryParamsRecord.id"
              placeholder="请输入病历号"
              clearable
              @keyup.enter.native="handleQueryRecord"
          />
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input
              v-model="queryParamsRecord.doctorName"
              placeholder="请输入主治医生姓名"
              clearable
              @keyup.enter.native="handleQueryRecord"
          />
        </el-form-item>
        <el-form-item label="医生编号" prop="doctorId">
          <el-input
              v-model="queryParamsRecord.doctorId"
              placeholder="请输入医生编号"
              clearable
              @keyup.enter.native="handleQueryRecord"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" size="mini" @click="handleQueryRecord">搜索</el-button>
          <el-button icon="refresh" size="mini" @click="resetQueryRecord">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading2" :data="recordList" highlight-current-row @current-change="handleCurrentChangeRecord">
        <el-table-column label="病历号" align="center" prop="number" />
        <el-table-column label="患者姓名" align="center" prop="patientName" />
        <el-table-column label="主治医生" align="center" prop="doctorName" />
        <el-table-column label="主述" align="center" prop="priDesc" />
        <el-table-column label="现有病史" align="center" prop="presentIllness" />
        <el-table-column label="现有病史治疗情况" align="center" prop="presentMedicalCondition" />
        <el-table-column label="会诊日期" align="center" prop="date" />
      </el-table>
      <pagination
          v-show="totalRecord>0"
          :total="totalRecord"
          v-model:page="queryParamsRecord.pageNum"
          v-model:limit="queryParamsRecord.pageSize"
          @pagination="getListRecord"
      />
    </el-dialog>


  </div>
</template>

<script>
import { listDiagnosis, getDiagnosis, delDiagnosis, addDiagnosis, updateDiagnosis } from "@/api/emr/diagnosis";
import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/emr/patient";
import {listRecordInfo } from "@/api/emr/add_prescription";

import {ElMessage} from "element-plus";
import {ref} from "vue";


export default {
  name: "Diagnosis",
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: true,
      // 标签页
      activeTab: ref(''),
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      totalRecord: 0,
      // 确诊信息表格数据
      recordList: [],
      // 总条数
      totalPatient: 0,
      // 患者表格数据
      patientList: [],
      // 弹出层标题
      titlePatient: "",
      titleRecord: "",
      title: "",
      // 是否显示弹出层
      openPatient: false,
      openRecord: false,
      open: false,
      // 当前病人
      currentPatient: null,
      // 当前病历
      currentRecord: null,
      currentRecordNumber: null,
      // 查询参数
      queryParamsPatient: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idNumber: null,
        phone: null,
        gender: null,
        age: null,
      },
      queryParamsRecord: {
        pageNum: 1,
        pageSize: 10,
        patientId: null,
        id: null,
        doctorName: null,
        doctorId: null,
      },
      // 患者表单参数
      formPatient: {},
      // 患者表单校验
      rulesPatient: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话号码不能为空且不能超过11位", trigger: "blur" }
        ],
      },
      // 确诊表单参数
      formDiagnosis: {},
      // 确诊表单校验
      rulesDiagnosis: {
        result: [
          { required: true, message: "诊断结果不能为空", trigger: "blur" }
        ],
        date: [
          { required: true, message: "确诊日期不能为空", trigger: "blur" }
        ]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }

    };
  },
  created() {
    this.getListPatient();
  },
  methods: {
    /** 查询信息列表 */
    getListPatient() {
      this.loading = true;
      listPatient(this.queryParamsPatient).then(response => {
        this.patientList = response.rows;
        this.totalPatient = response.total;
        this.loading = false;
      });
      this.loading = false;
    },
    getListRecord() {
      this.loading2 = true;
      this.queryParamsRecord.patientId = this.currentPatient.id;
      listRecordInfo(this.queryParamsRecord).then(response=>{
        this.recordList = response.rows;
        this.totalRecord = response.total;
      });
      this.loading2 = false;
    },
    getList() {
      this.loading = true;
      listDiagnosis(this.queryParamsPatient).then(response => {
        this.recordList = response.rows;
        this.totalRecord = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    resetPatientQuery(){
      this.queryParamsPatient ={
        pageNum: 1,
        pageSize: 10,
        name: null,
        idNumber: null,
        phone: null,
        gender: null,
        age: null,
      };
      this.resetForm("queryParamsPatient")
    },
    resetPatient() {
      this.form = {
        id: null,
        medicalRecordId: null,
        result: null,
        suggestion: null,
        attention: null,
        date: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    // 表单重置
    resetRecord() {
      this.form = {
        id: null,
        medicalRecordId: null,
        result: null,
        suggestion: null,
        attention: null,
        date: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        medicalRecordId: null,
        result: null,
        suggestion: null,
        attention: null,
        date: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 添加患者表单 */
    submitFormPatient() {
      this.$refs["formPatient"].validate(valid => {
        let s=this.formPatient.phone;
        let y=this.formPatient.idNumber;
        if ((s.length)<=11&&(y.length)==18)
        {
            if (valid) {
              if (this.formPatient.id != null) {
                updatePatient(this.formPatient).then(response => {
                  ElMessage({
                    message: '修改成功',
                    type: 'success',
                  });
                });
              } else {
                addPatient(this.formPatient).then(response => {
                  ElMessage({
                    message: '新增成功',
                    type: 'success',
                  });
                });
              }
            }
        }
        else{
          ElMessage({
          message: '电话号码长度不能超过11位或者身份证必须为18位',
          type: 'warning'
        });
         }
        
      });
    },
    /** 确诊提交 */
    submitFormDiagnosis() {
      if(this.currentPatient == null || this.currentPatient.id == null){
        ElMessage({
          message: '请选择患者',
          type: 'warning',
        });
        return;
      }
      if(this.currentRecord == null || this.currentRecord.id == null){
        ElMessage({
          message: '请选择病历',
          type: 'warning',
        });
        return;
      }else{
        this.formDiagnosis.medicalRecordId = this.currentRecord.id;
      }
      this.$refs["formDiagnosis"].validate(valid => {
        if (valid) {
          if (this.formDiagnosis.id != null) {
            updateDiagnosis(this.formDiagnosis).then(response => {
              ElMessage({
                message: '修改成功',
                type: 'success',
              });
            });
          } else {
            addDiagnosis(this.formDiagnosis).then(response => {
              ElMessage({
                message: '提交成功',
                type: 'success',
              });
            });
          }
        }
      });
    },
    /** 重置按钮操作 */
    resetFormPatient() {
      this.resetForm("formPatient");
      this.resetForm("formDiagnosis");
      this.formPatient.gender=null;
      this.currentPatient = null;
      this.currentRecordNumber = null;
      this.currentRecord = null;
      // this.handleQuery();
    },
    /** 重置按钮操作 */
    resetFormDiagnosis() {
      this.resetForm("formDiagnosis");
      // this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQueryPatient() {
      this.queryParamsPatient.pageNum = 1;
      this.getListPatient();
    },
    /** 重置按钮操作 */
    resetQueryPatient() {
      this.resetForm("queryParamsPatient");
      this.getListPatient();
      // this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQueryRecord() {
      this.queryParamsRecord.pageNum = 1;
      this.getListRecord();
    },
    /** 重置按钮操作 */
    resetQueryRecord() {
      this.resetForm("queryParamsRecord");
      // this.handleQuery();
    },
    // 患者单选选框选中数据
    handleCurrentChangePatient(selection) {
      if(selection){
        let param = {
          idNumber: selection.idNumber,
        }
        listPatient(param).then(response => {
          this.formPatient = response.rows[0];
          this.currentPatient = response.rows[0];
          this.currentRecord = null;
          this.recordList = null; // todo fixme
          this.currentRecordNumber = null;
          this.openPatient = false;
          if(ref('formDiagnosis')){
            this.resetFormDiagnosis();
          }
        });
      }
    },
    // 病历单选选框选中数据
    handleCurrentChangeRecord(selection) {
      // console.log(this.recordList);
      if(selection){
        if(this.recordList != null) {
          for (const obj of this.recordList) {
            if (obj.number === selection.number) {
              // alert(selection.number)
              this.currentRecord = obj;
              this.currentRecordNumber = selection.number;
            }
          }
        }
      }
      // 更新表单
      this.refreshDiagnosisForm();
      this.openRecord = false;
    },
    // 确诊表单tab点击事件
      handleTabChange (name){
      if(name === 'checkApply'){
        console.log('tab' + name);
      }
      else if(name === 'inspectApply'){
        console.log('tab' + name);
      }else if(name === 'handleApply'){
        console.log('tab' + name);
      }else{
        this.refreshDiagnosisForm();
      }
    },
    refreshDiagnosisForm(){
      if(this.currentRecord != null && this.currentRecord.id != null){
        let param = {
          medicalRecordId: this.currentRecord.id
        }
        listDiagnosis(param).then(response => {
          if(response.total >= 1){
            this.formDiagnosis = response.rows[0];
          }
        });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 选择患者按钮操作 */
    handlePatientSelect() {
      // this.reset();
      this.openPatient = true;
      this.titlePatient = "选择患者";
    },
    /** 选择病历按钮操作 */
    handleRecordSelect() {
      // this.reset();
      if(this.currentPatient == null || this.currentPatient.id == null){
        ElMessage({
          message: '请选择患者',
          type: 'warning'
        });
        return;
      }
      this.getListRecord();
      this.openRecord = true;
      this.titleRecord = "选择病历";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDiagnosis(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改确诊信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDiagnosis(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDiagnosis(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除确诊信息编号为"' + ids + '"的数据项？').then(function() {
        return delDiagnosis(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('emr/diagnosis/export', {
        ...this.queryParamsPatient
      }, `diagnosis_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
